package cn.tedu._03vehicle.base.interceptors;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;

import java.time.LocalDateTime;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 网站限流拦截器，限制单个IP每分钟之内访问网站的次数不能超过3次
 */
@Slf4j
public class RateLimitInterceotor implements HandlerInterceptor {
    private static final int MAX_COUNT=3;
    private static final int WINDOW_SIZE_SECONDS=60;

    // {"192.168.1.11":1,"192.168.1.22":2//,"192.168.1.33":3}
    private final ConcurrentHashMap<String,Integer>clientCounts = new ConcurrentHashMap<>();
    // {"192.168.1.11":"2025-06-16 00:00:00","192.168.1.22":"2025-06-15 18:00:00}
    private final ConcurrentHashMap<String, LocalDateTime> lastVisitTimes = new ConcurrentHashMap<>();
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String clientIp = request.getRemoteAddr();
        LocalDateTime lastVisitTime =lastVisitTimes.get(clientIp);
        /*
        如果（lastVisitTime是空值 或者 现在的时间 > lastVisitTime+60 ）{clientCounts中添加键值对【计数器清零】；lastVisitTimes中添加【更新】键值对}
         */
        if (lastVisitTime == null || LocalDateTime.now().isAfter(lastVisitTime.plusSeconds(WINDOW_SIZE_SECONDS))){
            clientCounts.put(clientIp,0);
            lastVisitTimes.put(clientIp,LocalDateTime.now());
        }
        //请求次数+1
        /*
        int a = clientCounts.get(clientIp)+1;
        clientCount.put(clientIp,a);
         */
        int count = clientCounts.merge(clientIp,1,Integer::sum);
        //获取当前IP的请求次数
        //如果当前IP的请求次数小于3次，则放行，否则拦截
        if (count > MAX_COUNT){
            throw new RuntimeException("访问过于频繁，请稍后再试");
        }
        return true;
    }
}
